package com.cn.wanxi.io;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.util.IO;
import com.sun.deploy.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NavIO {
    String spllit = "\n";

    public static void main(String[] args) {
        new NavIO().getNavModels();
    }

    public List<NavModel> getNavModels() {
        List<NavModel> list = new ArrayList<>();
        /**
         * 1.创建文件
         * 2.写
         * 3.读
         * 4.封装
         */
        File file = IO.create("nav.txt");
        write(file);
        String result = IO.read(file);
//        System.out.println(result);
        list = getList(result);
        return list;
    }


    private void write(File file) {
        try {
            OutputStream outputStream = new FileOutputStream(file);
//            CompanyDao companyDao = new CompanyDao();
            NavDao navDao = new NavDao();
//字符串转换为字节数组
//            String logo = companyDao.getLogo();
//            outputStream.write(logo.getBytes(), 10, 20);
//            得到的数据是字符串数组，公司信息是字符串。
//            写的时候必须转换成byte[]数组
            String[] titles = navDao.getTitles();
//            上一节课学了字符串转换为byte数组，所以需要将字符串数组转换为字符串
            String title = Arrays.toString(titles);
            outputStream.write(title.getBytes());
//            outputStream.write(StringUtils.join(Arrays.asList(titles), ",").getBytes());
            outputStream.write(spllit.getBytes());
            List<String> hrefs = navDao.getHrefs();
            outputStream.write(Arrays.toString(hrefs.toArray()).getBytes());
            outputStream.write(spllit.getBytes());
//            outputStream.write(StringUtils.join(Arrays.asList(hrefs.toArray()), ",").getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 封装list
     *
     * @param result
     * @return
     */
    private List<NavModel> getList(String result) {
        String[] results = result.split(spllit);
        String title = results[0];
//        replace替换
        title = title.replace("[", "");
        title = title.replace("]", "");
        title = title.replace(" ", "");
        String href = results[1];
        href = href.replace("[", "");
        href = href.replace("]", "");
        href = href.replace(" ", "");

        String[] hrefs = href.split(",");

        String[] titles = title.split(",");

        List<NavModel> navModelList = new ArrayList<>();
//        NavDao navDao = new NavDao();//对象实例化
        int length = hrefs.length;
        for (int i = 0; i < length; i++) {
            NavModel model = new NavModel();
            model.setTitle(titles[i]);
            model.setHref(hrefs[i]);
            navModelList.add(model);
        }
        return navModelList;
    }
}
